package main

import (
	"fmt"
	"net/http"
	"os"
	"path"
	"slices"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

func main() {
	router := gin.Default()

	router.POST("/upload", func(c *gin.Context) {
		//1、获取上传文件
		file, err := c.FormFile("file")
		if err == nil {
			//2、获取后缀名 判断类型是否正确 .jpg .png .gif .jpeg
			extName := path.Ext(file.Filename)
			//如果切片中不包含extName
			if !slices.Contains([]string{".jpg", ".png", ".gif", ".jpeg"}, extName) {
				c.JSON(http.StatusBadGateway, gin.H{
					"status": "failue",
					"msg":    "文件类型不正确",
				})
				return
			}
			//3、创建图片保存目录 static/upload
			day := time.Now().Format("20060102")
			dir := "./static/upload/" + day
			err := os.MkdirAll(dir, 0666)
			if err != nil {
				fmt.Println(err, "|", day, "|", dir, "|", 1111)
				c.String(200, "生成路径失败")
				return
			}

			//4、生成文件名称和保存的目录

			fileName := strconv.FormatInt(time.Now().Unix(), 10) + extName

			//5、执行上传
			dst := path.Join(dir, fileName)
			c.SaveUploadedFile(file, dst)
		}
		c.JSON(http.StatusOK, gin.H{
			"status": "success",
			"msg":    "上传成功",
		})
	})
	router.Run(":9000")
}
